package com.taobao.wolfwolf.taobao;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;

import com.taobao.api.*;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import com.taobao.wolfwolf.hibernate.pojo.ComposeColor;
import com.taobao.wolfwolf.hibernate.pojo.Pic;
import com.taobao.wolfwolf.hibernate.pojo.Product;
import com.taobao.wolfwolf.hibernate.pojo.Specification;
import com.taobao.wolfwolf.hibernate.pojo.Type;
import com.taobao.wolfwolf.hibernate.service.ProductService;
import com.taobao.wolfwolf.hibernate.service.UnitService;
import com.taobao.wolfwolf.taobao.SkuParse.Sku;
import com.taobao.wolfwolf.util.ApplicationContextUtil;
import com.taobao.wolfwolf.util.GB2Alpha;
import com.taobao.wolfwolf.util.Util;

public class ProductSync extends Taobao {

	private Product product = null;
	
	private ProductService ps;
	
	int i = 0;
	
	public ProductSync() {
		getPage();
	}

	/**
	 * 获取一个分页的商品
	 */
	public void getPage() {
		try {
			ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
			
			ps = (ProductService) ApplicationContextUtil.getBean("ProductService");
//			ItemsGetRequest req = new ItemsGetRequest();

			// 获取 num_iid, 用来获取商品详情
			req.setFields("num_iid");

			// 淘宝id名称
//			req.setNicks("myleft1");

			// 每页大小
			req.setPageSize(pageSize);
			
			for(long i = 1; i <= pageSize; i++) {
				// 页码
				req.setPageNo(i);
				
				// sessionKey
				ItemsOnsaleGetResponse response = client.execute(req, TaoBaoUtil.SESSIONKEY);

				getItems(response.getBody());
			}
			
			System.out.println("over");
			
		} catch (ApiException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取多个商品
	 * @param xmlBody
	 */
	@SuppressWarnings("unchecked")
	public void getItems(String xmlBody) {
		try {

			Document document = DocumentHelper.parseText(xmlBody);

			List<DefaultElement> list = document.selectNodes("//items_onsale_get_response/items/item");

			for (DefaultElement df : list) {
				
				Element num_iid = df.element("num_iid");
				
				long iid = Long.valueOf(num_iid.getText());
				if(ps.findByNumIId(iid) == null);
//					System.out.println(iid);

				ItemGetRequest req1 = new ItemGetRequest();
				req1.setFields("num_iid, created, title, detail_url, pic_url, property_alias, sku");
				req1.setNumIid(iid);

				ItemGetResponse response = client.execute(req1, TaoBaoUtil.SESSIONKEY);
				getItem(response.getBody());
				System.out.println(i++);
			}

		} catch (ApiException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取单个商品
	 * @param xmlBody
	 * @throws DocumentException
	 */
	@SuppressWarnings("unchecked")
	public void getItem(String xmlBody) throws DocumentException {
		Document doc = DocumentHelper.parseText(xmlBody);
		List<DefaultElement> l = doc.selectNodes("//item_get_response/item");
		
		product = new Product();
		for (DefaultElement d : l) {
			
			long num_iid = Long.valueOf(d.element("num_iid").getText());
//			System.out.println(num_iid);
			String title = d.element("title").getText();
			System.out.print(title);
			
			// Item的发布时间
			String created = d.element("created").getText();
			
			String detail_url = d.element("detail_url").getText();
			String pic_url = d.element("pic_url").getText();
			String alias = d.element("property_alias").getText();
			
			UnitService us = (UnitService) ApplicationContextUtil.getBean("UnitService");
			
			product.setNum_iid(num_iid);
			product.setName(title);
			product.setUnit(us.findById(1));
			
			product.setPinyin(GB2Alpha.String2Alpha(title));
			
			List<DefaultElement> sku = doc.selectNodes("//skus/sku");
			
			String[] split = alias.split(";");
			
			//ps.update(product);
			product.setHref(detail_url);
			product.setPic(new Pic(title, pic_url));
			product.setCreated(Util.getDate(created));
			
			getSku(sku, split, product);
			ps.saveOrUpdate(product);
		}
	}

	

	/**
	 * @param mw
	 * @param sku
	 * @param split
	 * @return
	 */
	private void getSku(List<DefaultElement> sku, String[] split, Product p) {
		for(DefaultElement s : sku) {
			String properties = s.element("properties").getText();
//			String quantity = s.element("quantity").getText();
			String price = s.element("price").getText();
			
			for(String tmp : split) {
				if(tmp.contains(properties)) {
					// 创建单个商品
					createSitem(price, tmp, p);
				}
			}
		}
	}

	/**
	 * 创建单个商品
	 * @param speces
	 * @param types
	 * @param tmpt
	 * @param price
	 * @param tmp
	 */
	private void createSitem(String price, String tmp, Product p) {
		Specification spec = null;
		Sku sk = SkuParse.getSku(tmp);
		
		String specs = sk.getSpecs();
		ComposeColor cc = sk.getCcolor();
		Type type = sk.getType();
		
		// 如果商品中已经有该类别，就不添加
		if(!p.getTypes().contains(type) && type != null) {
			p.getTypes().add(type);
		}
		// 如果规格不为空的话
		if(specs != null) {
			spec = new Specification();
			spec.setSizes(specs);
			spec.setPrice(Float.valueOf(price));
			
			if(!p.getSpeces().contains(spec)) {
				p.getSpeces().add(spec);
			}
		}
		
		if(cc != null && !p.getCcolors().contains(cc))
			p.getCcolors().add(cc);
	}
	
	public void output(String str) {
	    FileOutputStream fos;
		try {
			fos = new FileOutputStream("c:/sku.txt");
			Writer out = new OutputStreamWriter(fos, "utf-8");  
		    out.write(str);  
		    out.close();  
		    fos.close();  
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
	}
	
	public static void main(String[] args) {
		new ProductSync();
	}
}
